import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'dart:async';
import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../data/models/emotion_record.dart';
import '../data/repositories/emotion_repository.dart';
import '../data/repositories/emotion_repository_impl.dart';
import '../data/repositories/media_repository.dart' as media_repo;
import '../data/repositories/media_repository_impl.dart' as media_impl;
import '../core/utils/app_utils.dart';
import 'history_controller.dart';
import 'analytics_controller.dart';
import 'home_controller.dart';

/// 记录控制器
/// Record controller
class RecordController extends GetxController {
  // 数据仓库
  // Data repositories
  final EmotionRepository _emotionRepository = EmotionRepositoryImpl();
  final media_repo.MediaRepository _mediaRepository = media_impl.MediaRepositoryImpl();
  
  // 响应式状态变量
  // Reactive state variables
  final selectedEmotion = Rx<EmotionType?>(null);
  final emotionIntensity = 5.0.obs;
  final diaryContent = ''.obs;
  final selectedImages = <File>[].obs;
  final selectedAudios = <File>[].obs;
  final audioPath = ''.obs;
  final tags = <String>[].obs;
  final isLoading = false.obs;
  final isRecording = false.obs;
  final errorMessage = ''.obs;
  final recordingDuration = 0.obs; // 录音时长（秒）/ Recording duration in seconds
  
  // 控制器
  // Controllers
  final TextEditingController diaryController = TextEditingController();
  final TextEditingController tagController = TextEditingController();
  
  // 图片选择器
  // Image picker
  final ImagePicker _imagePicker = ImagePicker();
  
  // 录音控制器
  // Audio recorder controller
  late RecorderController _recorderController;
  
  // 录音文件路径
  // Recording file path
  String? _currentRecordingPath;
  
  // 录音计时器
  // Recording timer
  Timer? _recordingTimer;
  
  @override
  void onInit() {
    super.onInit();
    // 监听日记内容变化
    // Listen to diary content changes
    diaryController.addListener(() {
      diaryContent.value = diaryController.text;
    });
    
    // 初始化录音控制器
    // Initialize audio recorder controller
    _initializeRecorder();
  }
  
  @override
  void onClose() {
    diaryController.dispose();
    tagController.dispose();
    _recorderController.dispose();
    _recordingTimer?.cancel();
    super.onClose();
  }
  
  /// 初始化录音控制器
  /// Initialize audio recorder controller
  void _initializeRecorder() {
    _recorderController = RecorderController()
      ..androidEncoder = AndroidEncoder.aac
      ..androidOutputFormat = AndroidOutputFormat.mpeg4
      ..iosEncoder = IosEncoder.kAudioFormatMPEG4AAC
      ..sampleRate = 44100;
  }
  
  /// 设置选中的情绪类型
  /// Set selected emotion type
  void setSelectedEmotion(EmotionType emotion) {
    selectedEmotion.value = emotion;
    clearError();
  }
  
  /// 设置情绪（别名）
  /// Set emotion (alias)
  void setEmotion(EmotionType emotion) {
    setSelectedEmotion(emotion);
  }
  
  /// 设置强度（别名）
  /// Set intensity (alias)
  void setIntensity(double intensity) {
    setEmotionIntensity(intensity);
  }
  
  /// 获取选中的强度
  /// Get selected intensity
  double get selectedIntensity => emotionIntensity.value;
  
  /// 检查是否可以保存
  /// Check if can save
  bool get canSave {
    return selectedEmotion.value != null && 
           diaryContent.value.trim().isNotEmpty;
  }
  
  /// 设置日记内容
  /// Set diary content
  void setDiaryContent(String content) {
    diaryContent.value = content;
    diaryController.text = content;
  }
  
  /// 选择图片（别名）
  /// Pick image (alias)
  Future<void> pickImage() async {
    await addImage();
  }
  
  /// 设置情绪强度
  /// Set emotion intensity
  void setEmotionIntensity(double intensity) {
    emotionIntensity.value = intensity;
  }
  
  /// 添加图片
  /// Add image
  Future<void> addImage() async {
    try {
      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );
      
      if (image != null) {
        selectedImages.add(File(image.path));
        clearError();
      }
    } catch (e) {
      setError('添加图片失败: ${e.toString()}');
    }
  }
  
  /// 拍照添加图片
  /// Take photo and add image
  Future<void> takePhoto() async {
    try {
      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );
      
      if (image != null) {
        selectedImages.add(File(image.path));
        clearError();
      }
    } catch (e) {
      setError('拍照失败: ${e.toString()}');
    }
  }
  
  /// 移除图片
  /// Remove image
  void removeImage(int index) {
    if (index >= 0 && index < selectedImages.length) {
      selectedImages.removeAt(index);
    }
  }
  
  /// 添加标签
  /// Add tag
  void addTag(String tag) {
    if (tag.trim().isNotEmpty && !tags.contains(tag.trim())) {
      tags.add(tag.trim());
      tagController.clear();
    }
  }
  
  /// 移除标签
  /// Remove tag
  void removeTag(String tag) {
    tags.remove(tag);
  }
  
  /// 开始录音
  /// Start recording
  Future<void> startRecording() async {
    try {
      // 检查录音权限
      // Check recording permission
      final permission = await Permission.microphone.request();
      if (!permission.isGranted) {
        errorMessage.value = '需要麦克风权限才能录音';
        return;
      }
      
      // 生成录音文件路径
      // Generate recording file path
      final directory = await getApplicationDocumentsDirectory();
      final fileName = 'recording_${DateTime.now().millisecondsSinceEpoch}.m4a';
      _currentRecordingPath = '${directory.path}/$fileName';
      
      // 开始录音
      // Start recording
      await _recorderController.record(path: _currentRecordingPath!);
      
      isRecording.value = true;
      recordingDuration.value = 0;
      
      // 开始计时
      // Start timer
      _startRecordingTimer();
      
      print('录音开始: $_currentRecordingPath');
    } catch (e) {
      errorMessage.value = '录音开始失败: $e';
      isRecording.value = false;
      print('录音错误: $e');
    }
  }
  
  /// 停止录音
  /// Stop recording
  Future<void> stopRecording() async {
    try {
      if (!isRecording.value) return;
      
      // 停止录音
      // Stop recording
      final path = await _recorderController.stop();
      
      isRecording.value = false;
      _stopRecordingTimer();
      
      if (path != null && path.isNotEmpty) {
        // 添加录音文件到列表
        // Add recording file to list
        final audioFile = File(path);
        if (await audioFile.exists()) {
          selectedAudios.add(audioFile);
          audioPath.value = path;
          print('录音完成: $path');
        } else {
          errorMessage.value = '录音文件不存在';
        }
      } else {
        errorMessage.value = '录音文件路径为空';
      }
    } catch (e) {
      errorMessage.value = '录音停止失败: $e';
      isRecording.value = false;
      print('停止录音错误: $e');
    }
  }
  
  /// 开始录音计时器
  /// Start recording timer
  void _startRecordingTimer() {
    _recordingTimer?.cancel();
    _recordingTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      recordingDuration.value++;
    });
  }
  
  /// 停止录音计时器
  /// Stop recording timer
  void _stopRecordingTimer() {
    _recordingTimer?.cancel();
    _recordingTimer = null;
  }

  /// 移除所有音频
  /// Remove all audio
  void removeAudio() {
    audioPath.value = '';
    selectedAudios.clear();
  }
  
  /// 删除指定音频文件
  /// Delete audio file at index
  void removeAudioAt(int index) {
    if (index >= 0 && index < selectedAudios.length) {
      selectedAudios.removeAt(index);
    }
  }
  
  /// 保存情绪记录
  /// Save emotion record
  Future<void> saveRecord() async {
    if (!_validateForm()) {
      return;
    }
    
    try {
      isLoading.value = true;
      clearError();
      
      // 创建情绪记录
      // Create emotion record
      final record = EmotionRecord(
        id: AppUtils.generateUuid(),
        emotionType: selectedEmotion.value!,
        emotionIntensity: emotionIntensity.value.toInt(),
        diaryContent: diaryContent.value,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
      );
      
      // 保存记录到数据库
      // Save record to database
      await _emotionRepository.insertRecord(record);
      
      // 保存媒体文件
      // Save media files
      await _saveMediaFiles(record.id);
      
      // 重置表单
      // Reset form
      _resetForm();
      
      // 显示成功消息
      // Show success message
      Get.snackbar(
        '保存成功',
        '情绪记录已保存',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
      
      // 通知其他控制器刷新数据
      // Notify other controllers to refresh data
      _notifyDataRefresh();
      
      // 返回上一页
      // Go back to previous page
      Get.back();
      
    } catch (e) {
      setError('保存失败: ${e.toString()}');
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 保存媒体文件
  /// Save media files
  Future<void> _saveMediaFiles(String recordId) async {
    // 保存图片文件
    // Save image files
    for (final image in selectedImages) {
      final mediaFile = MediaFile(
        id: AppUtils.generateUuid(),
        recordId: recordId,
        filePath: image.path,
        fileSize: await image.length(),
        fileType: MediaFileType.image,
        createdAt: DateTime.now(),
      );
      
      await _mediaRepository.insertMediaFile(mediaFile);
    }
    
    // 保存音频文件
    // Save audio files
    for (final audio in selectedAudios) {
      final mediaFile = MediaFile(
        id: AppUtils.generateUuid(),
        recordId: recordId,
        filePath: audio.path,
        fileSize: await audio.length(),
        fileType: MediaFileType.audio,
        createdAt: DateTime.now(),
      );
      
      await _mediaRepository.insertMediaFile(mediaFile);
    }
  }
  
  /// 验证表单
  /// Validate form
  bool _validateForm() {
    if (selectedEmotion.value == null) {
      setError('请选择情绪类型');
      return false;
    }
    
    if (diaryContent.value.trim().isEmpty) {
      setError('请输入日记内容');
      return false;
    }
    
    return true;
  }
  
  /// 重置表单
  /// Reset form
  void _resetForm() {
    selectedEmotion.value = null;
    emotionIntensity.value = 5.0;
    diaryContent.value = '';
    diaryController.clear();
    selectedImages.clear();
    selectedAudios.clear();
    clearError();
  }
  
  /// 设置错误信息
  /// Set error message
  void setError(String message) {
    errorMessage.value = message;
  }
  
  /// 清除错误信息
  /// Clear error message
  void clearError() {
    errorMessage.value = '';
  }
  
  /// 通知其他控制器刷新数据
  /// Notify other controllers to refresh data
  void _notifyDataRefresh() {
    try {
      // 通知历史页面控制器刷新数据
      // Notify history controller to refresh data
      if (Get.isRegistered<HistoryController>()) {
        Get.find<HistoryController>().refreshData();
      }
      
      // 通知分析页面控制器刷新数据
      // Notify analytics controller to refresh data
      if (Get.isRegistered<AnalyticsController>()) {
        Get.find<AnalyticsController>().refreshData();
      }
      
      // 通知首页控制器刷新数据
      // Notify home controller to refresh data
      if (Get.isRegistered<HomeController>()) {
        Get.find<HomeController>().refreshData();
      }
    } catch (e) {
      print('通知数据刷新失败: $e');
    }
  }
  
  /// 获取情绪强度描述
  /// Get emotion intensity description
  String getIntensityDescription(double intensity) {
    if (intensity <= 2) {
      return '很轻微';
    } else if (intensity <= 4) {
      return '轻微';
    } else if (intensity <= 6) {
      return '中等';
    } else if (intensity <= 8) {
      return '强烈';
    } else {
      return '非常强烈';
    }
  }
}